#include "logger.h"
#include <iostream>
#include <time.h>

Logger &Logger::GetInstance()
{
    static Logger logger;
    return logger;
}

Logger::Logger()
{
    std::thread writeLogTask([&]() {
        for (;;)
        {

            time_t now = time(nullptr);
            tm *now_tm = localtime(&now);

            char filename[128];
            sprintf(filename, "%d-%d-%d-log.txt", now_tm->tm_year + 1900, now_tm->tm_mon + 1, now_tm->tm_mday);

            FILE *pf = fopen(filename, "a+");
            if (nullptr == pf)
            {
                std::cout << "logger file " << filename << " open error" << std::endl;
                exit(EXIT_FAILURE);
            }
            std::string msg = m_lckQue.Pop();
            char time_buf[128] = {0};
            snprintf(time_buf, 128, "%d:%d:%d [%s] => ", now_tm->tm_hour, now_tm->tm_min, now_tm->tm_sec,
                     ((m_loglevel == LogLevel::INFO) ? "INFO" : "ERROR"));
            msg.insert(0, time_buf);
            msg.push_back('\n');
            fputs(msg.c_str(), pf);
            fclose(pf);
        }
    });
    writeLogTask.detach();
}

void Logger::SetLogLevel(LogLevel level)
{
    m_loglevel = level;
}

void Logger::Log(std::string msg)
{
    m_lckQue.Push(msg);
}
